package com.print;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

import mycoffee.order.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;

import com.citizen.port.android.BluetoothPort;
import com.citizen.request.android.RequestHandler;

public class PrinterSampleActivity extends Activity {
	private final static String PASS_WORD = "123456";
	private static final String TAG = "BluetoothConnectMenu";
	// Intent request codes
	// private static final int REQUEST_CONNECT_DEVICE = 1;
	private static final int REQUEST_ENABLE_BT = 2;
	public static final String BT_DEVICE_ADDRESS = "DefaultDevice";
	private String currentDeviceAddress;
	ArrayAdapter<String> adapter;
	private BluetoothAdapter mBluetoothAdapter;
	private Vector<BluetoothDevice> remoteDevices;
	private Thread hThread;
	private static boolean connected;
	// BT
	private BluetoothPort bp;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// Setting
		bluetoothSetup();
		// Restore printer config
		SharedPreferences settings = getSharedPreferences(BT_DEVICE_ADDRESS, 0);
		String deviceAddress = settings.getString("deviceAddress", "");
		if (deviceAddress.equals("") == false){
			try {
				btConn(mBluetoothAdapter.getRemoteDevice(deviceAddress));
			} catch(Exception e)
			{
				// Bluetooth Address Format [OO:OO:OO:OO:OO:OO]
				Log.e(TAG,e.getMessage(),e);
				AlertView.showError(e.getMessage(), PrinterSampleActivity.this);
				return;	
			}
		}		
	}

	// called by button list item to link to list item activity
	public void onClickSetting(View v) {
		final Dialog dlgPass = new Dialog(this);
		dlgPass.setContentView(R.layout.password_dialog);
		dlgPass.setTitle(getString(R.string.admin_pass));
		final EditText etPassword = (EditText) dlgPass
				.findViewById(R.id.etAdminPassword);
		final Button btLogin = (Button) dlgPass.findViewById(R.id.btLogin);
		btLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (TextUtils
						.equals(PASS_WORD, etPassword.getText().toString())) {
					// start dialog to input password.
					// start dialog to input password.
					Intent intent = new Intent(getApplicationContext(),
							PrinterSettingDialog.class);
					startActivity(intent);
					dlgPass.dismiss();
				}
			}
		});
		dlgPass.show();
	}

	// called by button list item to link to list item activity
	public void onClickPrint(View v) {
		ESCPSample2 sample = new ESCPSample2();
		try {
			sample.sample1();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Show Error Dialog
	 * 
	 * @param string
	 */
	private void showErrorDialog(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		builder.show();
	}

	/**
	 * Set up Bluetooth.
	 */
	private void bluetoothSetup() {
		// Initialize
		clearBtDevData();
		bp = BluetoothPort.getInstance();
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			// Device does not support Bluetooth
			return;
		}
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);

			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		}
	}

	private void clearBtDevData() {
		setRemoteDevices(new Vector<BluetoothDevice>());
	}

	// Bluetooth Connection method.
	private void btConn(final BluetoothDevice btDev) throws IOException {
		new connTask().execute(btDev);
	}

	/** ======================================================================= */
	public class connTask extends AsyncTask<BluetoothDevice, Void, Integer> {
		private final ProgressDialog dialog = new ProgressDialog(
				PrinterSampleActivity.this);

		@Override
		protected void onPreExecute() {
			dialog.setTitle("Bluetooth");
			dialog.setMessage("Connecting");
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(BluetoothDevice... params) {
			Integer retVal = null;
			try {
				bp.connect(params[0]);
				retVal = new Integer(0);
			} catch (IOException e) {
				retVal = new Integer(-1);
			}
			return retVal;
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (result.intValue() == 0) {
				RequestHandler rh = new RequestHandler();
				hThread = new Thread(rh);
				hThread.start();
				connected = true;
			}
			if (dialog.isShowing()) {
				String cmsg;
				dialog.dismiss();
				if (connected) {
					// Save to config as default device
					SharedPreferences settings = getSharedPreferences(
							BT_DEVICE_ADDRESS, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("deviceAddress", currentDeviceAddress);

					// Commit the edits!
					editor.commit();

					cmsg = "Bluetooth Connected";
					showErrorDialog(cmsg);
					// Toast toast = Toast.makeText(PrinterSettingDialog.this,
					// cmsg,
					// Toast.LENGTH_LONG);
					// toast.show();
					// finish();
				} else {
					cmsg = "Bluetooth Not Connected.";
					AlertView.showError(cmsg, PrinterSampleActivity.this);
					// finish();
				}
			}
			super.onPostExecute(result);
		}
	}

	/**
	 * Bluetooth connection status.
	 * 
	 * @return connected - boolean
	 */
	public static boolean isConnected() {
		return connected;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			bp.disconnect();
		} catch (IOException e) {
			Log.e(TAG, e.getMessage(), e);
		}
		if ((hThread != null) && (hThread.isAlive())) {
			hThread.interrupt();
			hThread = null;
		}
	}

	public Vector<BluetoothDevice> getRemoteDevices() {
		return remoteDevices;
	}

	public void setRemoteDevices(Vector<BluetoothDevice> remoteDevices) {
		this.remoteDevices = remoteDevices;
	}
}